const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')

router.get('/get-user-comment-like', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { sqltype, page_index, page_size } = req.query
  if (
    !Bee.StringUtils.isNotBlank(sqltype) ||
    !Bee.StringUtils.isNumber(page_index * 1) ||
    !Bee.StringUtils.isNumber(page_size * 1)
  )
    return handleError(10003, '参数错误')

  // sqltype 个位数: 0 = 降序  1 = 升序
  const [getUserLikeError, getUserLike] = await to(
    db.query(
      `SELECT c.* FROM comment_like cl, comment c, userinfo ui WHERE cl.user_id = ? AND cl.comment_id = c.id AND ui.id = cl.user_id ORDER BY created_time ${
        Bee.StringUtils.getStrLast(sqltype, 1) === '0' ? 'DESC' : 'ASC'
      } LIMIT ?,?`,
      [
        validateTokenSuccess.id,
        (parseInt(page_index) - 1) * parseInt(page_size),
        parseInt(page_size),
      ]
    )
  )
  if (getUserLikeError || !getUserLike) return handleError(-1, getUserLikeError)

  const [getTotalError, Total] = await to(
    db.query(
      'SELECT count(*) FROM comment_like cl, comment c, userinfo ui WHERE cl.user_id = ? AND cl.comment_id = c.id AND ui.id = cl.user_id',
      [validateTokenSuccess.id]
    )
  )
  if (getTotalError || !Total) return handleError(-1, getTotalError)

  return resp.json({
    code: 0,
    msg: status_code[0],
    data: {
      list: getUserLike,
      total: Total[0]['count(*)'],
    },
  })
})

module.exports = router
